package com.borya.dao.impl;

import java.time.Clock;
import java.util.*;
import java.util.stream.Stream;

import com.borya.model.db.CitycodeRelate;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.borya.dao.UploadSourceDAO;
import com.borya.framework.annotation.Component;
import com.borya.framework.core.ServerSqlSession;
import com.borya.framework.util.ObjectUtils;
import com.borya.model.entity.CardSource;
import com.borya.model.entity.PhoneSource;
import com.borya.model.entity.SelectInfo;
import com.borya.util.DateUtils;

@Component("uploadSourceDAOImpl")
public class UploadSourceDAOImpl extends BaseDAOImpl implements UploadSourceDAO{

	private Logger log = Logger.getLogger(getClass());


	@Override
	public Map<String, String> saveSmsp() {
		try (ServerSqlSession session = getSqlDataSource().session();){
			StringBuilder sb = new StringBuilder(128);
			sb.append("select citycode,smsphone from t_smsphone ");
			sb.append(" where citycode != ''");
			return session.executeQuery(sb.toString(), rs-> {
				Map<String, String> map = new HashMap<>();
				if(rs != null){
					while(rs.next()){
						map.put(rs.getString(1), rs.getString(2));
					}
				}
				return map;
			});
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}

	@Override
	public boolean insertPhoneSource(List<PhoneSource> list) {
		final long nowTime = Clock.systemDefaultZone().millis();
		final String date = DateUtils.format(nowTime, "yyyy-MM-dd HH:mm:ss");
		List<String> sqlList = new ArrayList<String>();
		for(int i = 0,size=list.size();i<size;i++){
			PhoneSource source = list.get(i);
			if(! source.isSourceTrue()){
				continue;
			}
			setYtInsertSql(sqlList, source, date, nowTime, 1);

			if(i%100==99){
				if(sqlList.size() == 0){
					log.debug("入表数据 0");
					return true;
				}
				int[] inserts = executeBatch(sqlList);
				log.debug("入表数据 "+inserts.length);
				sqlList.clear();
			}
		}
		if(sqlList.size() == 0){
			log.debug("入表数据 0");
			return true;
		}
		int[] inserts = executeBatch(sqlList);
		log.debug("入表数据 "+inserts.length);
		return inserts != null && inserts.length>0;
	}

	/**
	 *
	 * @param sqlList
	 * @param source
	 * @param date
	 * @param nowTime
	 * @param type 1上传资料 2自动入库（需要删除中间表的数据）
	 */
	private void setYtInsertSql(List<String> sqlList, PhoneSource source,String date
			, long nowTime, int type){
		StringBuilder sb = new StringBuilder(256);
		/**先删除老数据再插入**/
		if(source.getMonopolyType() >= 0){
			sb.delete(0,sb.length());
			sb.append("delete from tb_phone_resource where number='").append(source.getPhone()).append("'");
			sqlList.add(sb.toString());
			if(source.getMonopolyType() == 1){
				sb.delete(0,sb.length());
				sb.append("delete from tb_monopoly_phone where number='").append(source.getPhone()).append("'");
				sqlList.add(sb.toString());
			} else if(source.getMonopolyType() == 2){
				sb.delete(0,sb.length());
				sb.append("delete from tb_private_phone where number='").append(source.getPhone()).append("'");
				sqlList.add(sb.toString());
			}
		}

//		if(ObjectUtils.isNullOrEmpty(source.getAid())){
			sb.delete(0,sb.length());
			sb.append("insert into tb_phone_resource set ");
			sb.append("number='").append(source.getPhone()).append("'");
			sb.append(",reverse_number='").append(new StringBuilder(source.getPhone()).reverse()).append("'");
			sb.append(",right_eight='").append(source.getRightEight()).append("'");
			if(source.getPhone().contains("4"))
			{
				sb.append(",with_four=1");
			}
			sb.append(",changeTime='").append(date).append("'");
			sb.append(",pretty=").append(source.getPretty());
			sb.append(",cityCode='").append(source.getCityCode()).append("'");
			sb.append(",createtime=").append(nowTime);
			sb.append(",recommendation=").append(source.getRecommendation());
			sb.append(",numberLevel=").append(source.getNumberLevel());
			sb.append(",resInstId='").append(source.getResInstId()).append("'");
			sb.append(",smsp='").append(source.getSmsp()).append("'");
			sb.append(",bigNumberLevel=").append(source.getBigNumberLevel());
			sb.append(",modify_time=").append(nowTime);
			sb.append(",source_dealerid='").append(source.getSourceDealerId()).append("'");
			sb.append(",phone_type=").append(source.getPhoneType());
			sb.append(",card_money=").append(source.getCardMoney());
			sb.append(",phone_model_type='").append(source.getPhoneModelType()).append("'");
			sb.append(",tf_phone_model_type='").append(source.getTfPhoneModelType()).append("'");
			if(source.getService_type() == 1){
				sb.append(",occupancy=0");
			} else {
				sb.append(",occupancy=5");
			}
			sb.append(",card_money_code='").append(source.getCardMoneyCode()).append("'");
			if(source.getLevelCode() != 0)
			{
				sb.append(",level_code=").append(source.getLevelCode());
			}
			if(source.getBigLevelCode() != 0)
			{
				sb.append(",big_level_code=").append(source.getBigLevelCode());
			}
			sb.append(",province_code=").append(source.getProvinceCode());
			sb.append(",left_three=").append(source.getLeftThree());
			sb.append(",phone_title=").append(source.getPhone(),0,7);
//		} else {
//			sb.append("update tb_phone_resource set ");
//			sb.append("changeTime='").append(date).append("'");
//			sb.append(",pretty=").append(source.getPretty());
//			sb.append(",cityCode='").append(source.getCityCode()).append("'");
//			sb.append(",createtime=").append(nowTime);
//			sb.append(",recommendation=").append(source.getRecommendation());
//			sb.append(",numberLevel=").append(source.getNumberLevel());
//			sb.append(",resInstId='").append(source.getResInstId()).append("'");
//			sb.append(",smsp='").append(source.getSmsp()).append("'");
//			sb.append(",bigNumberLevel=").append(source.getBigNumberLevel());
//			sb.append(",modify_time=").append(nowTime);
//			sb.append(",source_dealerid='").append(source.getSourceDealerId()).append("'");
//			sb.append(",phone_type=").append(source.getPhoneType());
//			sb.append(",card_money=").append(source.getCardMoney());
//			sb.append(",phone_model_type='").append(source.getPhoneModelType()).append("'");
//			sb.append(",tf_phone_model_type='").append(source.getTfPhoneModelType()).append("'");
//			if(source.getService_type() == 1){
//				sb.append(",occupancy=0");
//			} else {
//				sb.append(",occupancy=5");
//			}
//			sb.append(",card_money_code='").append(source.getCardMoneyCode()).append("'");
//			sb.append(" where ");
//			sb.append(" number='").append(source.getPhone()).append("'");
//		}
		sqlList.add(sb.toString());
		if(ObjectUtils.nonNullOrEmpty(source.getImsi())){
			sb.delete(0, sb.length());
			sb.append("insert into tb_imsi_resource set ");
			sb.append("city_code=").append(source.getCityCode());
			sb.append(",phone_head=").append(source.getPhone(),0,7);
			sb.append(",imsi='").append(source.getImsi()).append("'");
			sb.append(",create_time=").append(nowTime);
			sb.append(",modify_time=").append(nowTime);
			sb.append(",flag=1");
			sb.append(" on DUPLICATE key update ");
			sb.append("city_code=").append(source.getCityCode());
			sb.append(",phone_head=").append(source.getPhone(),0,7);
			sb.append(",imsi='").append(source.getImsi()).append("'");
			sb.append(",create_time=").append(nowTime);
			sb.append(",modify_time=").append(nowTime);
			sb.append(",flag=1");
			sqlList.add(sb.toString());
		}

		if(type == 2){
			sb.delete(0, sb.length());
			sb.append("update tb_auto_phone_resource set `status`=2");
			sb.append(" where id=").append(source.getId());
			sqlList.add(sb.toString());
		}
	}

	/**
	 *
	 * @param sqlList
	 * @param source
	 * @param date
	 * @param nowTime
	 * @param type 1上传资料2自动入库（需要删除中间表的数据）
	 */
	private void setUnAddSql(List<String> sqlList,PhoneSource source,final String date
			,final long nowTime, int type){
		StringBuilder sb = new StringBuilder(256);
		/**Aid为空则插入 否则为更新**/
		if(source.getMonopolyType() == -1){
			sb.append("insert into tb_phone_resource set ");
			sb.append("number='").append(source.getPhone()).append("'");
			sb.append(",right_eight='").append(source.getRightEight()).append("'");
			sb.append(",reverse_number='").append(new StringBuilder(source.getPhone()).reverse()).append("'");
			if(source.getPhone().contains("4"))
			{
				sb.append(",with_four=1");
			}
			sb.append(",changeTime='").append(date).append("'");
			sb.append(",pretty=").append(source.getPretty());
			sb.append(",cityCode='").append(source.getCityCode()).append("'");
			sb.append(",createtime=").append(nowTime);
			sb.append(",recommendation=").append(source.getRecommendation());
			sb.append(",numberLevel=").append(source.getNumberLevel());
			sb.append(",resInstId='").append(source.getResInstId()).append("'");
			sb.append(",smsp='").append(source.getSmsp()).append("'");
			sb.append(",bigNumberLevel=").append(source.getBigNumberLevel());
			sb.append(",modify_time=").append(nowTime);
			sb.append(",source_dealerid='").append(source.getSourceDealerId()).append("'");
			sb.append(",phone_type=").append(source.getPhoneType());
			sb.append(",card_money=").append(source.getCardMoney());
			sb.append(",phone_model_type='").append(source.getPhoneModelType()).append("'");
			if(source.getService_type() == 1){
				sb.append(",occupancy=0");
			} else {
				sb.append(",occupancy=5");
			}
			sb.append(",card_money_code='").append(source.getCardMoneyCode()).append("'");
			if(source.getLevelCode() != 0)
			{
				sb.append(",level_code=").append(source.getLevelCode());
			}
			if(source.getBigLevelCode() != 0)
			{
				sb.append(",big_level_code=").append(source.getBigLevelCode());
			}
			sb.append(",province_code=").append(source.getProvinceCode());
			sb.append(",left_three=").append(source.getLeftThree());
			sb.append(",phone_title=").append(source.getPhone(),0,7);
		} else {
			sb.append(" update tb_phone_resource set ");
			sb.append("changeTime='").append(date).append("'");
			sb.append(",pretty=").append(source.getPretty());
			sb.append(",cityCode='").append(source.getCityCode()).append("'");
			sb.append(",createtime=").append(nowTime);
			sb.append(",recommendation=").append(source.getRecommendation());
			sb.append(",numberLevel=").append(source.getNumberLevel());
			sb.append(",resInstId='").append(source.getResInstId()).append("'");
			sb.append(",smsp='").append(source.getSmsp()).append("'");
			sb.append(",bigNumberLevel=").append(source.getBigNumberLevel());
			sb.append(",modify_time=").append(nowTime);
			sb.append(",source_dealerid='").append(source.getSourceDealerId()).append("'");
			sb.append(",phone_type=").append(source.getPhoneType());
			sb.append(",card_money=").append(source.getCardMoney());
			sb.append(",phone_model_type='").append(source.getPhoneModelType()).append("'");
			if(source.getService_type() == 1){
				sb.append(",occupancy=0");
			} else {
				sb.append(",occupancy=5");
			}
			sb.append(",card_money_code='").append(source.getCardMoneyCode()).append("'");
			sb.append(" where number='").append(source.getPhone()).append("'");
		}

		sqlList.add(sb.toString());
		if(type == 2){
			sb.delete(0, sb.length());
			sb.append("update tb_auto_phone_resource set `status`=2");
			sb.append(" where id=").append(source.getId());
			sqlList.add(sb.toString());
		}
	}

	@Override
	public boolean insertUnicomPhoneSource(List<PhoneSource> list) {
		final long nowTime = Clock.systemDefaultZone().millis();
		final String date = DateUtils.format(nowTime, "yyyy-MM-dd HH:mm:ss");
		List<String> sqlList = new ArrayList<String>();
		for(int i = 0,size=list.size();i<size;i++){
			PhoneSource source = list.get(i);
			if(!source.isSourceTrue()){
				continue;
			}
			setUnAddSql( sqlList, source, date, nowTime, 1);
			if(i%100 == 99){
				if(sqlList.size() == 0){
					log.warn("入表数据 0");
					return true;
				}
				int[] inserts = executeBatch(sqlList);
				log.debug("入表数据 "+inserts.length);
				sqlList.clear();
			}
		}
		if(sqlList.size() == 0){
			log.warn("入表数据 0");
			return true;
		}
		int[] inserts = executeBatch(sqlList);
		log.debug("入表数据 "+inserts.length);
		return inserts != null && inserts.length>0;
	}

	@Override
	public boolean insertCardSource(List<CardSource> list) {
		try (ServerSqlSession session = getSqlDataSource().session();){
			final long nowTime = Clock.systemDefaultZone().millis();
			StringBuilder sb = new StringBuilder(2048);
			List<String> sqlList = new ArrayList<String>();
			for(int i = 0,size=list.size();i<size;i++){
				CardSource source = list.get(i);
				if(!source.isSourceTrue()){
					continue;
				}
				sb.delete(0, sb.length());
				sb.append("select id from tb_card_resource where ");
				sb.append(" iccid=?");
				String ids = session.executeQuery(sb.toString(), (rs)->{
					if(rs == null)
					{
						return null;
					}
					String id = "";
					while(rs.next())
					{
						id += rs.getString(1)+",";
					}
					return id;
				}, source.getIccid());
				if(StringUtils.isNotBlank(ids)){
					sb.delete(0, sb.length());
					sb.append("delete from tb_card_resource where ");
					sb.append("iccid='").append(source.getIccid()).append("'");
					int n = session.executeUpdate(sb.toString());
					log.debug("删除旧数据条数:"+n+",iccid:"+source.getIccid());
				}
				sb.delete(0, sb.length());
				sb.append("insert into tb_card_resource set ");
				sb.append("iccid='").append(source.getIccid()).append("'");
				sb.append(",card_resource_id='").append(source.getCardResourceId()).append("'");
				sb.append(",card_resource_id_jinan='").append(source.getCardResourceIdJN()).append("'");
				sb.append(",create_time=").append(nowTime);
				sb.append(",modify_time=").append(nowTime);
				sb.append(",card_type=").append(source.getCardType());
				sb.append(",iccid_19='").append(source.getIccid19()).append("'");
				sb.append(",city_code='").append(source.getCityCode()).append("'");
				sqlList.add(sb.toString());
				if(i%100 == 99){
					if(sqlList.size() == 0){
						log.debug("入表数据 0");
						return true;
					}
					int[] inserts = session.executeBatch(sqlList);
					log.debug("入表数据 "+inserts.length);
					sqlList.clear();
				}
			}
			if(sqlList.size() == 0){
				log.debug("入表数据 0");
				return true;
			}
			int[] inserts = session.executeBatch(sqlList);
			log.debug("入表数据 "+inserts.length);
			return inserts != null && inserts.length>0;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return false;
		}
	}

	@Override
	public List<PhoneSource> getPhoneResources(Map<String, SelectInfo> selMap) {
		try (ServerSqlSession session = getSqlDataSource().session();){
			StringBuilder sb = new StringBuilder(256);
			sb.append("select ");
			sb.append("b.id,b.phone_number,b.phone_type,b.city_code,b.inst_id,b.f_level,b.beforehand_fee,b.num_rule_kind,");
			sb.append("b.adjust_months,b.adjust_fee,b.work_no,b.unicom_dealer_id,b.special_disfee,");
			sb.append("b.belongs_to,b.imsi,b.service_type,a.monopoly_type");
			sb.append(" from tb_auto_phone_resource b left join tb_phone_resource a on b.phone_number=a.number");
			sb.append(" where b.`status`=0 limit 1000");
			return session.executeQuery(sb.toString(), rs-> {
				List<PhoneSource> list = new ArrayList<>();
				if(rs != null){
					while(rs.next()){
						PhoneSource each = new PhoneSource();
						each.setResInstId(rs.getString("inst_id"));
						each.setPhone(rs.getString("phone_number"));
						each.setCityCode(rs.getString("city_code"));
						String num_rule_kind = rs.getString("num_rule_kind");
						each.setNumberLevel("".equals(num_rule_kind)?"0":num_rule_kind);
						String f_level = rs.getString("f_level");
						each.setBigNumberLevel(("".equals(f_level)||"99".equals(f_level))?"0":f_level);
						each.setImsi(rs.getString("imsi"));
						each.setSourceDealerId(rs.getString("belongs_to"));
						each.setCardMoney(rs.getString("special_disfee"));
						each.setId(rs.getInt("id"));
						each.setUnicomDealerId(rs.getString("unicom_dealer_id"));
						each.setPhoneType(rs.getInt("phone_type"));
						each.setService_type(rs.getInt("service_type"));
						if(selMap.containsKey(each.getNumberLevel())){
							SelectInfo selectInfo = selMap.get(each.getNumberLevel());
							each.setLevelCode(selectInfo.getLevelCode());
							each.setBigLevelCode(selectInfo.getBigLevelCode());
						}
						String monopolyType = rs.getString("monopoly_type");
						if(Objects.isNull(monopolyType)){
							each.setMonopolyType(-1);
						} else {
							each.setMonopolyType(Integer.parseInt(monopolyType));
						}
						list.add(each);
					}
				}
				return list;
			});
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}

	@Override
	public List<CardSource> getCardResoutces() {
		try (ServerSqlSession session = getSqlDataSource().session();){
			StringBuilder sb = new StringBuilder(128);
			sb.append("select ");
			sb.append("b.id,b.iccid,b.card_type,b.city_code,b.inst_id,b.inst_id_jinan,b.inst_id_haerbin,");
			sb.append("b.card_company,b.card_belong,b.tf_dealer_id,b.device_type,a.id as aid");
			sb.append(" from tb_auto_card_resource b left join tb_card_resource a on b.iccid=a.iccid");
			sb.append(" where b.`status`=0 limit 1000");
			return session.executeQuery(sb.toString(), rs-> {
				List<CardSource> list = new ArrayList<>();
				if(rs != null){
					while(rs.next()){
						CardSource each = new CardSource();
						each.setIccid(rs.getString("iccid"));
						each.setCityCode(rs.getString("city_code"));
						each.setCardResourceIdJN(rs.getString("inst_id_jinan"));
						each.setCardResourceId(rs.getString("inst_id_haerbin"));
						each.setId(rs.getInt("id"));
						each.setCardType(rs.getInt("card_type"));
						each.setCardCompany(rs.getString("card_company"));
						each.setCardBelong(rs.getInt("card_belong"));
						each.setTfDealerId(rs.getString("tf_dealer_id"));
						each.setDeviceTpye(rs.getInt("device_type"));
						each.setAid(rs.getString("aid"));
						list.add(each);
					}
				}
				return list;
			});
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return null;
	}

	@Override
	public boolean insertAutoPhoneSource(List<PhoneSource> list) {
		final long nowTime = Clock.systemDefaultZone().millis();
		final String date = DateUtils.format(nowTime, "yyyy-MM-dd HH:mm:ss");
		List<String> sqlList = new ArrayList<>();
		for(int i = 0, size = list.size();i < size; i++){
			PhoneSource source = list.get(i);
			if(! source.isSourceTrue()){
				setFailPhoneSql(sqlList, source);
			}
			switch (source.getPhoneType()) {
			case 1:
				setYtInsertSql(sqlList, source, date, nowTime,2);
				break;
			case 2:
				setUnAddSql(sqlList, source, date, nowTime,2);
				break;
			default:
				break;
			}

			if(i%100==99){
				if(sqlList.size() == 0){
					log.debug("入表数据 0");
					return true;
				}
				executeBatch(sqlList);
				sqlList.clear();
			}
		}
		if(sqlList.size() == 0){
			return true;
		}
		int[] inserts = executeBatch(sqlList);
		return inserts != null && inserts.length>0;
	}

	private void setFailPhoneSql(List<String> sqlList,PhoneSource source){
		StringBuilder sb = new StringBuilder(128);
		sb.append("update tb_auto_phone_resource set ");
		sb.append("`status`=1");
		sb.append(",desc_str='").append(source.getDescStr()).append("'");
		sb.append(" where id=").append(source.getId());
	}

	@Override
	public boolean insertAutoCardSource(List<CardSource> list) {
		try (ServerSqlSession session = getSqlDataSource().session();){
			final long nowTime = Clock.systemDefaultZone().millis();
			StringBuilder sb = new StringBuilder(1024);
			List<String> sqlList = new ArrayList<String>();
			for(int i = 0,size=list.size();i<size;i++){
				CardSource source = list.get(i);
				if(! source.isSourceTrue()){
					sb.delete(0, sb.length());
					sb.append("update tb_auto_card_resource set ");
					sb.append("`status`=1,desc_str='").append(source.getDescStr()).append("'");
					sb.append(" where id=").append(source.getId());
					sqlList.add(sb.toString());
					continue;
				}
				if(ObjectUtils.nonNullOrEmpty(source.getAid())){
					sb.delete(0, sb.length());
					sb.append("delete from tb_card_resource where ");
					sb.append("iccid='").append(source.getIccid()).append("'");
					sqlList.add(sb.toString());
				}
				sb.delete(0, sb.length());
				sb.append("insert into tb_card_resource set ");
				sb.append("iccid='").append(source.getIccid()).append("'");
				sb.append(",card_resource_id='").append(source.getCardResourceId()).append("'");
				sb.append(",card_resource_id_jinan='").append(source.getCardResourceIdJN()).append("'");
				sb.append(",create_time=").append(nowTime);
				sb.append(",modify_time=").append(nowTime);
				sb.append(",card_type=").append(source.getCardType());
				sb.append(",iccid_19='").append(source.getIccid19()).append("'");
				sb.append(",city_code='").append(source.getCityCode()).append("'");
				sb.append(",card_company='").append(source.getCardCompany()).append("'");
				sb.append(",card_belong=").append(source.getCardBelong());
				sb.append(",tf_dealer_id='").append(source.getTfDealerId()).append("'");
				sb.append(",device_type=").append(source.getDeviceTpye());
				sqlList.add(sb.toString());
				sb.delete(0, sb.length());
				sb.append("update tb_auto_card_resource set `status`=2");
				sb.append(" where id=").append(source.getId());
				sqlList.add(sb.toString());
				if(i%100 >= 99){
					if(sqlList.size() == 0){
						return true;
					}
					session.executeBatch(sqlList);
					sqlList.clear();
				}
			}
			if(sqlList.size() == 0){
				return true;
			}
			int[] inserts = session.executeBatch(sqlList);
			return inserts != null && inserts.length>0;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return false;
		}
	}

	@Override
	public Map<String, String> saveNumberRule() {
		try (ServerSqlSession session = getSqlDataSource().session();){
			StringBuilder sb = new StringBuilder(128);
			sb.append("select unicom_dealer_id,numbr_model from tb_num_rule_code ");
			return session.executeQuery(sb.toString(), rs-> {
				Map<String, String> map = new HashMap<>();
				if(rs != null){
					while(rs.next()){
						map.put(rs.getString(1), rs.getString(2));
					}
				}
				return map;
			});
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}

	@Override
	public boolean updLog() {
		try (ServerSqlSession session = getSqlDataSource().session();) {
			List<String> sqlList = new ArrayList<>();
			StringBuilder sb = new StringBuilder(256);
			sb.append("select a.phone_type,group_concat(a.cityCode) from ");
			sb.append("(select phone_type,cityCode from tb_phone_resource group by phone_type,cityCode) a");
			sb.append(" group by a.phone_type");
			String[] citys = session.executeQuery(sb.toString(), rs-> {
				if(rs != null){
					String yt = "";
					String un = "";
					while(rs.next()){
						if(rs.getInt(1) == 1){
							yt = rs.getString(2);
						} else {
							un = rs.getString(2);
						}
					}
					return new String[]{yt,un};
				}
				return null;
			});
			if(ObjectUtils.isNull(citys)){
				log.warn("查询所有城市返回null");
				return false;
			}
			sb.delete(0,sb.length());
			sb.append("select group_concat(a.title) from ");
			sb.append("(select left(number,3) as title from tb_phone_resource group by left(number,3))a");
			String titles = session.executeQuery(sb.toString(), rs->{
				return (rs != null && rs.next())?rs.getString(1):null;
			});
			if(ObjectUtils.isNull(titles)){
				log.warn("查询所有号段返回null");
				return false;
			}

			sb.delete(0,sb.length());
			sb.append("update tb_citycode set open_yuante=1 where cityCode in (").append(citys[0]).append(")");
			sqlList.add(sb.toString());
			sb.delete(0,sb.length());
			sb.append("update tb_citycode set open_unicom=1 where cityCode in (").append(citys[1]).append(")");
			sqlList.add(sb.toString());
//			sb.delete(0,sb.length());
//			sb.append("update tb_source_upd_log set upd_date='").append(date).append("'");
//			sb.append(" where key_str='city'");
//			sqlList.add(sb.toString());
//			sb.delete(0,sb.length());
//			sb.append("update tb_source_upd_log set upd_date='").append(date).append("'");
//			sb.append(",val_str='").append(titles).append("'");
//			sb.append(" where key_str='phone_title'");
//			sqlList.add(sb.toString());
			int[] res = session.executeBatch(sqlList);
			log.debug("upd log :"+Arrays.toString(res));
			return (res!= null && res.length>0);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return false;
		}
	}


	@Override
	public Map<String, SelectInfo> getLevelCode() {
		try (ServerSqlSession session = getSqlDataSource().session();) {
			StringBuilder sb = new StringBuilder(256);
			sb.append("select code,val,special_type");
			sb.append(" from tb_select_rule where type=1");
			return session.executeQuery(sb.toString(),rs->{
				Map<String, SelectInfo> map = new HashMap<>();
				if(rs != null){
					while(rs.next()){
						SelectInfo selectInfo = new SelectInfo();
						selectInfo.setLevelCode(rs.getInt(1));
						selectInfo.setBigLevelCode(getBigCode(rs.getInt(3)));
						Stream.of(rs.getString(2).split(","))
								.forEach(x->{map.put(x,selectInfo);});
					}
				}
				return map;
			});
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	private int getBigCode(int specialType){
		int code;
		switch (specialType){
			case 1:
				code = 110000;
				break;
			case 3:
				code = 130000;
				break;
			default:
				code = 120000;
				break;
		}
		return code;
	}


	@Override
	public Map<String, CitycodeRelate> allCityInfo() {
		try (ServerSqlSession session = getSqlDataSource().session();) {
			StringBuilder sb = new StringBuilder(256);
			sb.append("select cityCode,cityName,provinceName,province_code");
			sb.append(" from tb_citycode");
			return session.executeQuery(sb.toString(),rs->{
				Map<String, CitycodeRelate> map = new HashMap<>();
				if(rs != null){
					while(rs.next()){
						CitycodeRelate citycodeRelate = new CitycodeRelate();
						citycodeRelate.setCityCode(rs.getString(1));
						citycodeRelate.setCityName(rs.getString(2));
						citycodeRelate.setProvinceName(rs.getString(3));
						citycodeRelate.setProvinceCode(rs.getInt(4));
						map.put(rs.getString(1),citycodeRelate);
					}
				}
				return map;
			});
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}
}
